package utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	/**
	 * 位图操作
	 *@date 2015-11-27 下午1:13:37
	 *@author zhouhonghui
	 */
	public class BitmapUtil
	{
		public function BitmapUtil()
		{
		}
		/**
		 * 翻转位图,先水平翻转,再垂直翻转 
		 * @param bmData
		 * @return 
		 * 
		 */		
		public static function tipperBD(bmData:BitmapData):BitmapData
		{
			bmData = tipperBDHorizontal(bmData);
			bmData = tipperBDVertical(bmData);
			return bmData;
		}
		
		/**
		 * 水平翻转位图 <br>		
		 * @param bmp
		 * @return 
		 * 
		 */		
		public static function tipperBDHorizontal(bmData:BitmapData):BitmapData
		{
			var tmpBmp:Bitmap = new Bitmap(bmData);
			tmpBmp.scaleX = -1;
			var sp:Sprite = new Sprite();		
			sp.addChild(tmpBmp);
			var src:BitmapData = new BitmapData(bmData.width,bmData.height,true,0x00FFFFFF);
			var m:Matrix = new Matrix();			
			m.tx = bmData.width;
			src.draw(sp,m);				
			return src;
		}
		/**
		 * 垂直翻转 
		 * @param bmp
		 * @return 
		 * 
		 */		
		public static function tipperBDVertical(bmData:BitmapData):BitmapData
		{
			var tmpBmp:Bitmap = new Bitmap(bmData);
			tmpBmp.scaleY = -1;
			var sp:Sprite = new Sprite();		
			sp.addChild(tmpBmp);
			var src:BitmapData = new BitmapData(bmData.width,bmData.height,true,0x00FFFFFF);
			var m:Matrix = new Matrix();			
			m.ty = bmData.height;
			src.draw(sp,m);				
			return src;
		}
		
		/**
		 * 获取UI的有效像素区域 (不透明区域)
		 * @param ui
		 * @return 
		 * 
		 */		
		public static function getUIAlphaRect(ui:DisplayObject):Rectangle
		{			
			var bm:BitmapData = new BitmapData(ui.width,ui.height,true,0);
			bm.draw(ui);
			var rect:Rectangle = bm.getColorBoundsRect(0xFF000000, 0, false);
			return rect;
		}
		/**
		 * 获取ui对象某点处的32位颜色值 <br>
		 * (比如实现透明区域不响应鼠标事件)
		 * @param x
		 * @param y
		 * @param uiObj
		 * @return 
		 * 
		 */		
		public static function getPixel32(x:Number,y:Number,uiObj:DisplayObject):uint
		{
			var rect:Rectangle = uiObj.getBounds(uiObj);
			var mt:Matrix = new Matrix();
			var bmData:BitmapData = new BitmapData(rect.width,rect.height,true,0);
			mt.translate(-rect.x,-rect.y);
			bmData.draw(uiObj,mt);			
			var pixel:uint = bmData.getPixel32(Math.abs(rect.x)+x,Math.abs(rect.y)+y);			
			return pixel;
		}
		
		//向右旋转90度 
		public static function scaleRight(bmp:BitmapData):BitmapData
		{ 
			var m:Matrix = new Matrix(); 
			m.rotate(Math.PI/2); 
			m.translate(bmp.height,0); 
			var bd:BitmapData = new BitmapData(bmp.height, bmp.width,false); 
			bd.draw(bmp,m); 
			return bd; 
		} 
		//向左旋转90度 
		public static function scaleLeft(bmp:BitmapData):BitmapData{ 
			var m:Matrix = new Matrix(); 
			m.rotate(-Math.PI/2); 
			m.translate(0,bmp.width); 
			var bd:BitmapData = new BitmapData(bmp.height, bmp.width,false); 
			bd.draw(bmp,m); 
			return bd; 
		}
	}
}